/**
 * Created by zlp on 2018/01/24.
 * For 我的账户
 */
var API = require("../support/const");



var request = require('superagent')
    , fs = require('fs')
    , svgCaptcha = require('svg-captcha');

let result = {
    common: {}
};

//短信验证码
exports.sendSMS = function (req, res, next) {

    res.json({
        "status": 0,
        "msg": ""
    })
};

//邮箱唯一验证
exports.emailUnique = function (req, res, next) {
    let params = {
        email: req.body.email
    };
    request.get(`${API.common.email_unique}`)
        .query({msg: JSON.stringify(params)})
        .end(function (_req, _res) {
            //记录用户操作日志
            res.json(JSON.parse(_res.text));
        });
};

//邮箱验证码
exports.sendMail = function (req, res, next) {
    let params = {
        email: req.body.email
    };
    request.get(`${API.common.send_email_verify_code}`)
        .query({msg: JSON.stringify(params)})
        .end(function (_req, _res) {
            //记录用户操作日志
            if (_res) {
                res.json(JSON.parse(_res.text));
            }
        });
};

//获取汇率
exports.getRate = function (req, res, next) {
    let params = {
        rate_type: req.body.rate_type
    };
    // deposit_exchangerate	入金
    // withdraw_exchangerate	出金
    request.get(`${API.common.get_rate}`)
        .query({msg: JSON.stringify(params)})
        .end(function (_req, _res) {
            //记录用户操作日志
            res.json(JSON.parse(_res.text));
        });
};

//上传图片
exports.upload = function (req, res, next) {
    let user=JSON.parse(unescape(req.cookies.user))
    if (req.file) {
        let {roleType, roleId} = req.body;
        roleType=roleType || 1
        roleId = roleId || user.role_id

        request.post(`${API.common.upload_img}`)
            .field('roleType', roleType)
            .field('roleId', roleId)
            .attach('uploadFileName', req.file.path)
            .end(function (_req, _res) {
                if (_res.status == 200) {
                    fs.unlink(req.file.path, function () {

                        res.json(JSON.parse(_res.text));


                    });
                }
                //   res.json(JSON.parse(_res.text));
            });
    }
};


//上传文件
exports.uploadFile = function (req, res, next) {
    let user=JSON.parse(unescape(req.cookies.user))
    if (req.file) {
        let {roleType, roleId} = req.body;
        roleType=roleType || 1
        roleId = roleId || user.role_id
        request.post(`${API.common.upload_file}`)
            .field('roleType', roleType)
            .field('roleId', roleId)
            .attach('uploadFileName', req.file.path)
            .end(function (_req, _res) {
                if (_res.status == 200) {
                    fs.unlink(req.file.path, function () {

                        res.json(JSON.parse(_res.text))
                    });
                }
                //  res.json(JSON.parse(_res.text));
            });
    }
};

exports.getFile = function(req,res,next){
    let id = req.body.id || req.params.id
    console.log('req id =',id)
    request.get(`${API.common.get_file}${id}`)
        .end(function (_req, _res) {
            res.send(_res.text);
        });

}
exports.fileUrl = function(req,res,next){
    let id = req.body.id || req.params.id
    console.log('req id =',id)
    request.get(`${API.common.get_file}${id}`)
        .end(function (_req, _res) {
            res.send(_res.text);
        });

}

//获取图形验证码
exports.captcha = {
    get: function (req, res, option) {
        const captcha = svgCaptcha.create({fontSize: 50, width: 150, height: 38});

        req.session.captcha = captcha.text;
        res.setHeader('Content-Type', 'image/svg+xml');
        res.write(String(captcha.data));
        res.end();
    },
    check: function (req, res, next) {
        let code = req.body.code
        let result = {
            status: 200,
            msg: "success"
        };
        if (req.session.captcha) {
            if (code.toLowerCase() != req.session.captcha.toLowerCase()) {
                result.status = 0
                result.msg = "验证码错误"
            }
        }

        res.json(result)
    }
};

//获取访问资源地址
exports.resourceUrl = function (req, res) {
    res.send('')
    // request.get(API.common.resource_url)
    //     .end(function (_req, _res) {
    //
    //         res.send(_res.text);
    //     });

};

//获取图片地址
exports.images = function (req, res) {

    let id = req.body.id || req.params.id

    request.get(`${API.common.get_img}${id}`)
        .end(function (_req, _res) {
           res.send(_res.text);
        });

};

exports.showImages = function (req, res) {
    let id = req.body.id || req.params.id
    request.get(`${API.common.get_img_liu}${id}`)
        .end(function (_req, _res) {

            let imgsrc = JSON.parse(_res.text).datas

            if(imgsrc){
                //TODO: 此处是为了，当获取图片链接失败时，返回的{}在前端图片不能立即加载出来，多条数据会出现卡克，故此处添加一个错误链接
                imgsrc = imgsrc === "{}" ? API.common.get_img_liu + 'edu/bd9cdf8fc62349228a23c4b0c1698323.jpg' : imgsrc;
                request(imgsrc).pipe(res)
            }


        });


};
var path = require("path");

exports.getFileBlob = function (req,res){
   /* var dirPath = path.join(__dirname, "file");
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath);
        console.log("文件夹创建成功");
    } else {
        console.log("文件夹已存在");
    }


    let {url,fileName} = req.body

    let stream = fs.createWriteStream(path.join(dirPath, fileName));
    request(url).pipe(stream).on("close", function (err) {
        console.log("文件[" + fileName + "]下载完毕");
    });*/
    /*let {url,fileName} = req.body
    request(url).pipe(fs.createWriteStream(fileName))*/

     /*   .pipe(fs.createWriteStream())
        .on('close', function() {
            console.log(close)
          /!*  var bu = fs.createReadStream(fpath, {start: 0, end: 262});
            bu.on('data', function(chunk) {
                console.log(chunk.toString());//这是结果
            });*!/
        });*/
}



let mimeType = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml"
}
